package com.practice.zookeeper.client;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import com.practice.zookeeper.client.zk.IServiceDiscovery;

public class RemoteInvocationHandler implements InvocationHandler {
	
	private IServiceDiscovery discovery;
	private String version;

	public RemoteInvocationHandler(IServiceDiscovery discovery, String version) {
		this.discovery = discovery;
		this.version = version;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		String className = method.getDeclaringClass().getName();
		
		RpcRequest request = new RpcRequest();
		request.setClassName(className);
		request.setMethodName(method.getName());
		request.setParameters(args);
		request.setVersion(version);
		
		String serviceAddress = discovery.discovery(className);
		
		RpcTcpTransport transpost = new RpcTcpTransport(serviceAddress);
		return transpost.send(request);
	}

}
